package guiCode;

import gui.uploadManager;
import java.io.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import com.sun.rowset.CachedRowSetImpl;

import basic.ClientConsole;
import flexibility.showMessage;
import flexibility.uploadFileInfo;
import flexibility.userData;

/**
 * This class is in charge for upload file process
 * 
 * 
 */
public class uploadManagerCode {

	ClientConsole start_connection;
	/**
	 * byteArray - stores the file's data as byte array type
	 */
	byte[] byteArray; // For storing the data of the uploaded file
	private JFrame frame;
	private Integer fileID;
	public Boolean uploadSuccess = true;
	private Integer userID;
	private userData DBData = new userData();
	private CachedRowSetImpl crs;
	private showMessage msg = new showMessage();

	public uploadManagerCode(ClientConsole str_conn, JFrame parent) {
		start_connection = str_conn;
		frame = parent;
	}

	/**
	 * Find a file to upload
	 */
	public File findFile() {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		int result = fileChooser.showOpenDialog(frame);
		if (result == JFileChooser.CANCEL_OPTION) {
			frame.dispose();
			return null;

		}
		File file = fileChooser.getSelectedFile();
		if ((file == null) || (file.getName().equals(""))) {
			JOptionPane.showMessageDialog(frame, "Invalid File Name",
					"Invalid File Name", JOptionPane.ERROR_MESSAGE);
			frame.dispose();
		}
		return file;
	}

	/**
	 * Upload the selected file
	 * 
	 */
	public void uploadfile(File file, uploadFileInfo fileInfo) {

		// Get the last fileID uploaded by the user

		Integer LastFileID = this.getLastFileID();
		System.out.println("LastFileID is: " + LastFileID);

		// Upload the selected file to data base
		userData fileData = new userData();
		System.out.println("ifUpdate is: " + fileInfo.getIfUpdate());
		if (fileInfo.getIfUpdate() == true) {
			msg.showMessages(frame, "Updating the existed file","Upload status", 0);
			fileData.addData(47); // fileData[0]=query ID to update the existing
									// file
			
			//In case the student wants to update the committed file , but the deadline has passed
			if (fileInfo.getIfLate()){
				System.out.println("Updates the field Last Submmision");
				this.updateLateSubmission(fileInfo);
			}
				
		} else {
			fileData.addData(41); // fileData[0]=query ID to insert a new file
		}

		fileData.addData(2); // fileData[1]=type - upload file to DB
		fileData.addData(file.getName()); // fileData[2]=file_name
		fileData.addData((int) file.length()); // fileData[3]=file_size
			
		// Check the file size
		if ((long) file.length() > 1048576) {
			msg.showMessages(frame,	"Can't upload ! The file must be up to 1MB","Upload error", 1);
			uploadSuccess=false;
			frame.dispose();
		} else { // Convert the file data into byte array
			byteArray = new byte[(int) file.length()];
			try {
				InputStream inStr = new BufferedInputStream(
						new FileInputStream(file));
				int offset = 0;
				int numRead = 0;
				while (offset < byteArray.length
						&& (numRead = inStr.read(byteArray, offset,
								byteArray.length - offset)) >= 0) {
					offset += numRead;
				}
				// Ensure all the bytes have been read in
				if (offset < byteArray.length) {
					throw new IOException("Could not completely read file "
							+ file.getName());
				}
				inStr.close();

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// Read in the bytes
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			fileData.addData(byteArray); // fileData[4]=the data of the file as
											// byte array
			fileData.addData(userID); // fileData[5]= userID

			if (fileInfo.getIfUpdate() == true) {// If the file should update
													// the existing one
				fileData.addData(fileInfo.getFileID()); // fileData[6]= fileID
			}
			start_connection.acceptMsg(fileData); // send parameters for
													// uploading file
			crs = start_connection.getResults();// this will get the results
												// from the server

			if (fileInfo.getIfUpdate() == false) {
				// Check if the file was uploaded
				fileID = this.getLastFileID();
				if (fileID > LastFileID) {
					uploadSuccess = true;
				} else {
					fileID = -1;
					uploadSuccess = false;
				}
			}
			frame.dispose();
		}
	}

	public void setFileID(Integer id) {
		fileID = id;
	}

	public Integer getFileID() {
		return fileID;
	}

	public void setUserID(Integer id) {
		userID = id;
	}

	/**
	 * The following method returns the last uploaded fileID by the user
	 * @return fileID 
	 */
	private Integer getLastFileID() {
		userData LastFileID = new userData();
		LastFileID.addData(43);
		LastFileID.addData("1");
		LastFileID.addData(userID);

		start_connection.acceptMsg(LastFileID);
		crs = start_connection.getResults();// this will get the results from
											// the server

		try {
			crs.next();
			if (crs.wasNull()) {
				return 0;
			} else
				return crs.getInt(1);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
		return 0;
	}

	/**
	 * This method updates the DataBase tables according to user's uploaded file
	 * @param fileInfo  - object of uploadFileInfo which includes the all information to update the DataBase 
	 */
	public void updateTables(uploadFileInfo fileInfo) {
		Integer teacherFileType = null;

		switch (fileInfo.getRole()) {
		case 1:
			break;
		case 2:
			break;
		case 3:
			DBData.deleteAll();
			System.out.println(fileInfo.getCourseID());
			
			teacherFileType = fileInfo.getTeacherFileType();
			if (teacherFileType == 0) { // In case teacher uploads a new
										// assignment
				DBData.addData(32); // query line
				DBData.addData(0); // write to data base type
				DBData.addData(fileInfo.getCourseID());
				DBData.addData(fileInfo.getTeacherID());
				DBData.addData(fileInfo.getSemesterID());
				DBData.addData(fileID); // fileID
				//DBData.addData(0); // if close
				
				start_connection.acceptMsg(DBData);
				crs = start_connection.getResults();// this will get the results
													// from the server
			} else if (teacherFileType == 1) {
				System.out.println("Updatetables, type= "+fileInfo.getTeacherFileType());
				//Uploading evaluation file 
				DBData.addData(101);
				DBData.addData(1);
				DBData.addData(fileInfo.getAssignmentID());
				DBData.addData(fileInfo.getStudentID());
				System.out.println("assignmentID, type= "+fileInfo.getAssignmentID());
				System.out.println("studentID, type= "+fileInfo.getStudentID());
				start_connection.acceptMsg(DBData);
				CachedRowSetImpl crs1 = start_connection.getResults();
				try {
					if(crs1.next()){
						// update Suitable record in DB
						System.out.println("Not empty");
						DBData.deleteAll();
						DBData.addData(102);
						DBData.addData(0);
						DBData.addData(fileID);
						DBData.addData(fileInfo.getAssignmentID());
						DBData.addData(fileInfo.getStudentID());						
						start_connection.acceptMsg(DBData);
						crs = start_connection.getResults();
					}
					else{
						//Insert new record
						System.out.println("Empty");
						DBData.deleteAll();
						DBData.addData(103);
						DBData.addData(0);
						DBData.addData(fileInfo.getAssignmentID());
						DBData.addData(fileInfo.getStudentID());
						DBData.addData(fileID);
						start_connection.acceptMsg(DBData);
						crs = start_connection.getResults();
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
				

			} else if (teacherFileType == 2) {
				//Uploading comments file
				System.out.println("Updatetables, type= "+fileInfo.getTeacherFileType());
				//Uploading evaluation file 
				DBData.addData(101);
				DBData.addData(1);
				DBData.addData(fileInfo.getAssignmentID());
				DBData.addData(fileInfo.getStudentID());
				System.out.println("assignmentID, type= "+fileInfo.getAssignmentID());
				System.out.println("studentID, type= "+fileInfo.getStudentID());
				start_connection.acceptMsg(DBData);
				CachedRowSetImpl crs1 = start_connection.getResults();
				try {
					if(crs1.next()){
						// update Suitable record in DB
						System.out.println("Not empty");
						DBData.deleteAll();
						DBData.addData(109);
						DBData.addData(0);
						DBData.addData(fileID);
						DBData.addData(fileInfo.getAssignmentID());
						DBData.addData(fileInfo.getStudentID());						
						start_connection.acceptMsg(DBData);
						crs = start_connection.getResults();
					}
					else{
						//Insert new record
						System.out.println("Empty");
						DBData.deleteAll();
						DBData.addData(110);
						DBData.addData(0);
						DBData.addData(fileInfo.getAssignmentID());
						DBData.addData(fileInfo.getStudentID());
						DBData.addData(fileID);
						start_connection.acceptMsg(DBData);
						crs = start_connection.getResults();
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			}

			break;
		case 4:
			DBData.deleteAll();
			DBData.addData(45); // query line
			DBData.addData(0); // write to data base type
			DBData.addData(userID); // studentID
			DBData.addData(fileInfo.getAssignmentID()); // assignmentID
			DBData.addData(fileInfo.getSemesterID()); // semesterID
			DBData.addData(fileInfo.getAssignmentCommitDate()); // commitDate
			DBData.addData(fileID); // fileID
			if (fileInfo.getIfLate()){ //shows if the submission of student's assignment was late 
				DBData.addData("Late Submission");
			}
			else{
				DBData.addData("");
			}
			start_connection.acceptMsg(DBData);
			crs = start_connection.getResults();// this will get the results
												// from the server
			break;
		}

	}
	
	/**
	 * this method updates the assignmentvsstudent table with Late Submission, 
	 * in case the student wants to update his committed assignment file, but hw has passed the deadline
	 */
	public void updateLateSubmission(uploadFileInfo fileInfo){
		DBData.deleteAll();
		DBData.addData(122);
		DBData.addData(0);
		System.out.println("StudentID: "+fileInfo.getStudentID());
		System.out.println("AssignmentID: "+fileInfo.getAssignmentID());
		DBData.addData(fileInfo.getAssignmentCommitDate());
		DBData.addData(fileInfo.getStudentID());
		DBData.addData(fileInfo.getAssignmentID());
		start_connection.acceptMsg(DBData);
		crs = start_connection.getResults();
	}
	

}
